﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;

/// <summary>
/// Summary description for URLRewriter
/// </summary>
public class URLRewriter : IHttpModule
{
    public void Dispose()
    {
    }

    // Add event handlers to the HttpApplication.
    public void Init(HttpApplication httpApp)
    {
        httpApp.BeginRequest += new EventHandler(OnBeginRequest);
    }

    // Record the time of the begin request event.
    public void OnBeginRequest(Object sender, EventArgs e)
    {
        HttpApplication application = (HttpApplication)sender;  
        HttpContext context = application.Context;  
        HttpResponse response = context.Response;
        String file = context.Request.Path;
        //String file = System.IO.Path.GetFileName(path);

        //重写后的URL地址  
        Regex regex = new Regex("-{1}([\\w%]+)=([\\w%\\s]+)", RegexOptions.Compiled);  
        MatchCollection matchs=regex.Matches(file);
       
        //如果满足URL地址重写的条件
        String query = "?";
        for (int i=0; i< matchs.Count; i++)
        {  
            String key = matchs[i].Groups[1].Value;
            String value = matchs[i].Groups[2].Value;
            query += key + "=" + value + "&";
        }

        if (query.Length > 1)
        {
            // remove the last &
            char[] arr = { '&' };
            query = query.TrimEnd(arr);

            MatchEvaluator ev = new MatchEvaluator(ReplaceCC);
            file = regex.Replace(file, ev);
            file += query;

            context.RewritePath(file);
        }
    }

    public String ReplaceCC(Match m)
    {
        return "";
    }

}
